package com.ycfmedical.bed.present;

import com.ycfmedical.bed.Constants;
import com.ycfmedical.bed.ControlBedConstants;
import com.ycfmedical.bed.factory.OrderFactory;
import com.ycfmedical.bed.serverdata.DBUtil;
import com.ycfmedical.bed.ui.ControlActivity;
import com.ycfmedical.bed.utils.ConvertOrderCheckoutUtil;
import com.ycfmedical.bed.utils.ServerControl;
import com.ycfmedical.bed.wifi.WifiEvent;

import android.os.Handler;

import cn.droidlover.xdroidmvp.log.XLog;
import cn.droidlover.xdroidmvp.mvp.XPresent;
import me.jessyan.rxerrorhandler.handler.RetryWithDelay;
import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by Administrator on 2017/3/17 0017.
 */

public class ControlPresenter extends XPresent<ControlActivity>
{

    WifiEvent wifi = WifiEvent.getInstance();
    
    String oldOrderMsg;
    String QuicklyPostMsg = "";
    DBUtil dbUtil = DBUtil.getInstance();
    
    Handler mhandler = new Handler();
    
    // 自由调整（发送区域和上下操作）
    public void FreedomPost(int btnNum, boolean numeration)
    {
        // 数据指令(未校验)
        String freedomPostStr = "";
        // 数据指令(已校验)
        String commandFreedom = "";
        // 增加
        if (numeration)
        {
            switch (btnNum)
            {
                case 1:
                    // 头部上升指令
                    freedomPostStr = OrderFactory.getMessage(ControlBedConstants.CONTROL_POST_HEAD_UP);
                    break;
                case 2:
                    // 腿部上升指令
                    freedomPostStr = OrderFactory.getMessage(ControlBedConstants.CONTROL_POST_LEG_UP);
                    break;
                case 3:
                    //
                    freedomPostStr = OrderFactory.getMessage(ControlBedConstants.CONTROL_POST_BODY_UP);
                    break;
                default:
                    break;
            }
            
        }
        // 减小
        else
        {
            switch (btnNum)
            {
                case 1:
                    freedomPostStr = OrderFactory.getMessage(ControlBedConstants.CONTROL_POST_HEAD_DOWN);
                    break;
                case 2:
                    freedomPostStr = OrderFactory.getMessage(ControlBedConstants.CONTROL_POST_LEG_DOWN);
                    break;
                case 3:
                    freedomPostStr = OrderFactory.getMessage(ControlBedConstants.CONTROL_POST_BODY_DOWN);
                    break;
                default:
                    break;
            }
            
        }
        commandFreedom = ConvertOrderCheckoutUtil.instructCheckOut(freedomPostStr);
        // 发送指令
        sendOrderMessage(commandFreedom);
        
    }
    
    public void FreedomFinish()
    {
        String freedomFinishStr = OrderFactory.getMessage(ControlBedConstants.CONTROL_POST_FINISH);
        freedomFinishStr = ConvertOrderCheckoutUtil.instructCheckOut(freedomFinishStr);
        // 发送指令
        sendOrderMessage(freedomFinishStr);
    }

    private String getQuicklyPostMsg(int PostID){
        return ServerControl.getQuicklyPostDate(PostID);
    }
    // 一键体位（发送指令，三个角度一个高度）
    public void QuicklyPost(int PostID)
    {
        
        String quicklyPostStr = "";// 数据指令(未校验)

        Observable.just(getQuicklyPostMsg(PostID))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .retryWhen(new RetryWithDelay(3, 2))//遇到错误时重试,第一个参数为重试几次,第二个参数为重试的间隔
                .subscribe(new Subscriber<String>() {
                               @Override
                               public void onCompleted()
                               {
                                   if(!isUnsubscribed())
                                   {
                                       this.unsubscribe();
                                   }
                                   loadQuicklyPostSData(quicklyPostStr,PostID);
                               }

                               @Override
                               public void onError(Throwable e) {
                                   XLog.e(getTag(), "PostID = " + PostID+ "  ;" + e);
                               }

                               @Override
                               public void onNext(String msg) {
                                   if(null != msg && !msg.equals("0"))
                                   QuicklyPostMsg = msg;
                               }
                           }
                );
    }

    // 加载数据库体位数据
    private void loadQuicklyPostSData(String quicklyPostStr,int PostID){
        if (QuicklyPostMsg.length() == 46 && !Constants.bedId.equals("13"))
        {
            //角度指令转换为一键体位指令
            if (ConvertOrderCheckoutUtil.angleMsgChangeQuicklyMsg(PostID,QuicklyPostMsg).length() == 46)
            {
                quicklyPostStr = ConvertOrderCheckoutUtil.angleMsgChangeQuicklyMsg(PostID,QuicklyPostMsg);
            }
            else
            {
                quicklyPostStr = Constants.wrongOrderMsg;
            }
        }
        else
        {
            // 默认体位数据
            switch (PostID)
            {
                // 睡眠体位
                case 1:
                    quicklyPostStr = OrderFactory.getMessage(ControlBedConstants.CONTROL_POST_SLEEP);
                    break;
                // 休闲体位
                case 2:
                    quicklyPostStr = OrderFactory.getMessage(ControlBedConstants.CONTROL_POST_RELAXATION);
                    break;
                // 就餐体位
                case 3:
                    quicklyPostStr = OrderFactory.getMessage(ControlBedConstants.CONTROL_POST_REPAST);
                    break;
                // 工作体位
                case 4:
                    quicklyPostStr = OrderFactory.getMessage(ControlBedConstants.CONTROL_POST_WORK);
                    break;
                default:
                    break;
            }
        }
        // ConvertOrderCheckoutUtil.instructCheckOut(quicklyPostStr);
        sendOrderMessage(quicklyPostStr);
    }
    
    // 护理体位(身高)
    public void SendStatureProgress(int bedHeight)
    {
        String orderMsg = "";
        orderMsg = OrderFactory.getMessage(ControlBedConstants.CONTROL_NURSE_STATURE_CHANGE)
            + ConvertOrderCheckoutUtil.integerC10T16(bedHeight) + "00000000000000000000000000000000";
        String orderMsgHeight = ConvertOrderCheckoutUtil.calculateBedHeight(orderMsg, bedHeight);
        String orderMessageHeight = ConvertOrderCheckoutUtil.instructCheckOut(orderMsgHeight);
        sendOrderMessage(orderMessageHeight);
        
    }
    
    // 护理体位(倾斜角度)
    public void sendSlantAngleProgress(int slantAngle)
    {
        String orderMsg = OrderFactory.getMessage(ControlBedConstants.CONTROL_SLANT_ANGLE);
        String orderMsgSlantAngle = ConvertOrderCheckoutUtil.calculateBedHeight(orderMsg, slantAngle);
        String orderMessageSlantAngle = ConvertOrderCheckoutUtil.instructCheckOut(orderMsgSlantAngle);
        sendOrderMessage(orderMessageSlantAngle);
    }
    
    // CRP(急救体位（发送特定指令）)
    public void Crp()
    {
        String CrpPostStr = "";
        CrpPostStr =
            ConvertOrderCheckoutUtil.instructCheckOut(OrderFactory.getMessage(ControlBedConstants.CONTROL_POST_CRP));
        // 发送指令与数据
        sendOrderMessage(CrpPostStr);
    }
    
    // 保存体位()
    public void savePost(String angleOrderMsg, int quicklyPostId)
    {
        ServerControl.SaveQuicklyPostDate(angleOrderMsg,quicklyPostId);
    }
    
    // 发送指令流程
    public void sendOrderMessage(String SendMessage)
    {
        oldOrderMsg = SendMessage;
        // 发送指令
        wifi.senddata(SendMessage);
    }
}
